import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Observable } from 'rxjs'
import { PERMISSION_KEY } from '@/decorators/permission.decorator'
import { UsersService } from '@/users/users.service'

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private readonly reflector: Reflector,
    private readonly userService: UsersService
  ) {}
  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const req = context.switchToHttp().getRequest()
    const user = req.user
    const permissions =
      this.reflector.getAllAndOverride<string[]>(PERMISSION_KEY, [
        context.getClass(),
        context.getHandler(),
      ]) || []
    console.log('=======permissions=====', permissions)
    if (!permissions.length) return true

    return this.userService.verfiyAutorify(user.userId, permissions)
  }
}
